import { reactive } from "vue";
import type { FormRules } from "element-plus";
import { isPhone, isEmail } from "@pureadmin/utils";

/** 自定义表单规则校验 */
export const formRules = reactive(<FormRules>{
  username: [
    { required: true, message: "账号名称为必填项", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value.length < 4 || value.length > 20) {
          callback(new Error("账号名称长度在4到20个字符之间"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  name: [
    { required: true, message: "用户名称为必填项", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value.length < 2) {
          callback(new Error("用户名称长度需大于2个字符"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  password: [
    { required: true, message: "用户密码为必填项", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value.length > 9 || value.length < 6) {
          callback(new Error("密码长度在6到8个字符之间"));
        } else {
          callback();
        }
      },
      trigger: "click"
    }
  ],
  phone: [
    { required: true, message: "手机号为必填项", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value === "") {
          callback();
        } else if (!isPhone(value)) {
          callback(new Error("请输入正确的手机号码格式"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  email: [
    {
      validator: (rule, value, callback) => {
        if (!isEmail(value) && value != "") {
          callback(new Error("请输入正确的邮箱格式"));
        } else {
          callback();
        }
      },
      trigger: "change"
    }
  ]
});
